﻿(function (window, $) {

    var attach = function ($els) {
        $els.each(function () {

            var $el = $(this);

            function trigger(ev) {
                var event = $.Event('tapup');
                event.originalEvent = ev.originalEvent;
                $el.trigger(event);
            }

            function touchend(ev) {
                ev.preventDefault();
                trigger(ev);
            }

            function mouseout(ev) {
                // if element is outside, then trigger
                if ($el.has(ev.relatedTarget).length == 0) {
                    trigger(ev);
                }
            }

            $el.on("touchleave.tapup touchcancel.tapup touchend.tapup", touchend);
            $el.on("mouseup.tapup", trigger);
            $el.on("mouseout.tapup", mouseout);
        });
    };

    var detach = function ($els) {
        return $els.off(".tapup");
    };

    $.event.special.tapup = {
        add: function (handleObj) {
            attach($(this));
        },
        remove: function (handleObj) {
            detach($(this));
        }
    };


}(this, jQuery));